package com.xiaoyu.izf.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.xiaoyu.izf.aspect.RequestAuth;
import com.xiaoyu.izf.model.*;
import com.xiaoyu.izf.model.page.DataTableBean;
import com.xiaoyu.izf.model.page.FormResultBean;
import com.xiaoyu.izf.model.page.ParamListBean;
import com.xiaoyu.izf.model.page.Status;
import com.xiaoyu.izf.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * 用户
 */
@Controller
@RequestMapping("/user")
public class UserInfoController extends BaseController{

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private VipInfoService vipInfoService;
    @Autowired
    private VipOrderService vipOrderService;
    @Autowired
    private CommissionGetLogService commissionGetLogService;
    @Autowired
    private ManualVipUpgradeLogService manualVipUpgradeLogService;
    @Autowired
    private RegionService regionService;
    @Autowired
    private UserCardInfoService userCardInfoService;

    /**
     * 用户列表页面
     * @param request
     * @return
     */
    @RequestMapping("/list_page")
    @RequestAuth
    public String userListPage(HttpServletRequest request, Model model){
        List<VipInfo> vipInfos = vipInfoService.vipInfos();
        model.addAttribute("vipInfos",vipInfos);
        return "mgr/user/user_list";
    }

    /**
     * 用户列表数据
     * @param request
     * @param body
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    @ResponseBody
    @RequestAuth
    public DataTableBean list(HttpServletRequest request, @RequestBody String body) throws IOException {
        UserInfo user = user(request);
        System.err.println(body);
        ParamListBean paramListBean = getParamListBean(body);
        DataTableBean dataTableBean = userInfoService.list(paramListBean,user);
        return dataTableBean;
    }

    /**
     * 下级合伙用户列表
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/second_list_page")
    @RequestAuth
    public String llUserListPage(HttpServletRequest request, int id,Model model){
        UserInfo user = userInfoService.adminUserOne(id);
        model.addAttribute("user",user);
        return "mgr/user/second_user_list";
    }

    /**
     * 下级合伙用户列表数据
     * @param request
     * @param body
     * @return
     * @throws IOException
     */
    @RequestMapping("/second_list")
    @ResponseBody
    @RequestAuth
    public DataTableBean secondList(HttpServletRequest request, @RequestBody String body) throws IOException {
        ParamListBean paramListBean = getParamListBean(body);
        DataTableBean dataTableBean = userInfoService.secondList(paramListBean);
        return dataTableBean;
    }

    @RequestMapping("/par_list_page")
    @RequestAuth
    public String parUserListPage(HttpServletRequest request, Model model){
        List<VipInfo> vipInfos = vipInfoService.vipInfos();
        model.addAttribute("vipInfos",vipInfos);
        return "mgr/user/par_user_list";
    }

    @RequestMapping("/par_list")
    @ResponseBody
    @RequestAuth
    public DataTableBean parList(HttpServletRequest request, @RequestBody String body) throws IOException {
        UserInfo user = user(request);
        ParamListBean paramListBean = getParamListBean(body);
        DataTableBean dataTableBean = userInfoService.list(paramListBean,user);
        return dataTableBean;
    }

    /**
     * 用户vip等级修改页面
     * @param request
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/vip_mod_page")
    @RequestAuth
    public String pwdModPage(HttpServletRequest request,int id,Model model) {
        UserInfo user = userInfoService.adminUserOne(id);
        model.addAttribute("user",user);
        List<VipInfo> vipInfos = vipInfoService.vipInfos();
        List<Region> provinces = regionService.provinces();
        model.addAttribute("provinces",provinces);
        model.addAttribute("vipInfos",vipInfos);
        return "/mgr/user/vip_mod";
    }

    /**
     * 用户vip等级修改
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/mod")
    @ResponseBody
    @RequestAuth
    public FormResultBean mod(HttpServletRequest request, int id,int vipType,
                              int provinceRegionId,
                              Integer countyRegionId) {
        FormResultBean fr = new FormResultBean(Status.HTTP_OK.value());
        UserInfo userInfo = userInfoService.adminUserOne(id);
        if(userInfo==null){
            return fr.setType("error").setMessage("修改数据不存在");
        //管理员不能升级vip
        }else if(userInfo.getIsAdmin()==1){
            return fr.setType("error").setMessage("该用户是管理员，不允许升级");
        }
        boolean canUpVip = userInfoService.canUpVip(userInfo,vipType);
        if (!canUpVip){
            return fr.setType("error").setMessage("升级VIP失败");
        }

        //省级服务商或区县服务商需选择对应的地区
        Region region = null;
        if (vipType==21){
            region = regionService.findByRegionId(provinceRegionId);
            if (region==null){
                return fr.setType("error").setMessage("请选择省份");
            }else if (region.getSoldOut()!=null&&region.getSoldOut()==1){
                return fr.setType("error").setMessage("升级失败，省级服务商已出售");
            }else {
                userInfo.setRegionCode(region.getRegionCode());
            }
        }else if (vipType==23){
            if (countyRegionId==null){
                return fr.setType("error").setMessage("请选择区/县");
            }
            region = regionService.findByRegionId(countyRegionId);
            if (region==null){
                return fr.setType("error").setMessage("请选择区/县");
            }else if (region.getSoldOut()!=null&&region.getSoldOut()==1){
                return fr.setType("error").setMessage("升级失败，区县服务商已出售");
            }else {
                userInfo.setRegionCode(region.getRegionCode());
            }
        }

        //添加vip升级日志
        manualVipUpgradeLogService.add(userInfo.getId(),userInfo.getVipType(),vipType);

        userInfo.setVipType(vipType);
        userInfoService.userVipUpdateByUser(userInfo);
        //userInfoService.save(userInfo);
        return fr.setType("success").setMessage("升级VIP成功");
    }

    /**
     * 用户基本信息修改页面
     * @param request
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/info_mod_page")
    @RequestAuth
    public String modPage(HttpServletRequest request,int id,Model model) {
        UserInfo user = userInfoService.adminUserOne(id);
        model.addAttribute("user",user);
        return "/mgr/user/user_mod";
    }

    /**
     * 用户基本信息修改
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/info_mod")
    @ResponseBody
    @RequestAuth
    public FormResultBean userInfoMod(HttpServletRequest request, int id,String nickName,String officialServiceNumber) {
        FormResultBean fr = new FormResultBean(Status.HTTP_OK.value());
        UserInfo userInfo = userInfoService.adminUserOne(id);
        if(userInfo==null){
            return fr.setType("error").setMessage("修改数据不存在");
        }

        if ((!userInfo.getOfficialServiceNumber().equals(officialServiceNumber))&&(!userInfo.getOfficialServiceNumberView().equals(officialServiceNumber))){
            if (userInfoService.adminUserByOfficialServiceNumber(officialServiceNumber)!=null){
                return fr.setType("error").setMessage("授权码已存在");
            }else {
                if (officialServiceNumber.contains("CAZF")){
                    userInfo.setOfficialServiceNumber(officialServiceNumber.substring(5));
                }else {
                    userInfo.setOfficialServiceNumber(officialServiceNumber);
                }
            }
        }

        userInfo.setNickName(nickName);
        userInfoService.save(userInfo);

        return fr.setType("success").setMessage("修改成功");
    }

    /**
     * 推广人信息页面
     * @param request
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/pusher_page")
    @RequestAuth
    public String pusherPage(HttpServletRequest request,int id,Model model) {
        UserInfo user = userInfoService.adminUserOne(id);
        model.addAttribute("user",user);
        if (user.getPushUid()>0) {
            model.addAttribute("pusher", userInfoService.adminUserOne(user.getPushUid()));
        }
        if (user.getGradePushUid()>0) {
            model.addAttribute("gradePusher", userInfoService.adminUserOne(user.getGradePushUid()));
        }
        return "/mgr/user/pusher_info2";
    }

    /**
     * 添加用户页面
     * @param request
     * @return
     */
    @RequestMapping("/add_page")
    @RequestAuth
    public String addPage(HttpServletRequest request,Model model){
        List<VipInfo> vipInfos = vipInfoService.vipInfos();
        List<Region> provinces = regionService.provinces();
        model.addAttribute("vipInfos",vipInfos);
        model.addAttribute("provinces",provinces);
        return "mgr/user/user_add";
    }

    /**
     * 添加用户
     * @return
     */
    @RequestMapping("/add")
    @RequestAuth
    @ResponseBody
    public FormResultBean userAdd(HttpServletRequest request,UserInfo user,
                                  String pusherPhone,int provinceRegionId,
                                  Integer countyRegionId){
        FormResultBean fr = new FormResultBean(Status.HTTP_OK.value());
        if(!Validator.isMobile(user.getUserName())){
            return fr.setType("error").setMessage("手机号码不正确");
        }
        if (userInfoService.adminUserByUserName(user.getUserName())!=null){
            return fr.setType("error").setMessage("用户已存在");
        }

        //省级服务商或区县服务商需选择对应的地区
        Region region = null;
        if (user.getVipType()==21){
            region = regionService.findByRegionId(provinceRegionId);
            if (region==null){
                return fr.setType("error").setMessage("请选择省份");
            }else if (region.getSoldOut()!=null&&region.getSoldOut()==1){
                return fr.setType("error").setMessage("添加失败，省级服务商已出售");
            }else {
                user.setRegionCode(region.getRegionCode());
            }
        }else if (user.getVipType()==23){
            if (countyRegionId==null){
                return fr.setType("error").setMessage("请选择省份");
            }
            region = regionService.findByRegionId(countyRegionId);
            if (region==null){
                return fr.setType("error").setMessage("请选择区/县");
            }else if (region.getSoldOut()!=null&&region.getSoldOut()==1){
                return fr.setType("error").setMessage("添加失败，区县服务商已出售");
            }else {
                user.setRegionCode(region.getRegionCode());
            }
        }

        UserInfo pusher = null;
        if(!StringUtils.isEmpty(pusherPhone)) {
            if (!Validator.isMobile(pusherPhone)) {
                return fr.setType("error").setMessage("手机号码不正确");
            }
             pusher = userInfoService.adminUserByUserName(pusherPhone);
            if (pusher == null) {
                return fr.setType("error").setMessage("推广人不存在");
            }
        }

        if (userInfoService.adminUserByOfficialServiceNumber(user.getOfficialServiceNumber())!=null){
            return fr.setType("error").setMessage("官方授权码已存在");
        }

        userInfoService.add(user.getOfficialServiceNumber(),user.getUserName(),user.getNickName(),user.getVipType(),pusher,user.getRegionCode());
        return new FormResultBean(Status.HTTP_OK.value(),"success","添加成功");
    }

    /**
     * 禁用用户
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/disabled")
    @ResponseBody
    @RequestAuth
    public FormResultBean disable(HttpServletRequest request,int id) {
        FormResultBean fr = new FormResultBean();
        UserInfo user = userInfoService.adminUserOne(id);
        user.setIsDel(1);
        userInfoService.save(user);
        fr.setType("success");
        fr.setMessage("操作成功。");
        return fr;
    }

    /**
     * 确认到账
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("/accountable")
    @ResponseBody
    @RequestAuth
    public FormResultBean accountable(HttpServletRequest request,int id) {
        FormResultBean fr = new FormResultBean();
        UserInfo user = userInfoService.adminUserOne(id);
        //vipOrderService.orderAdd(user,10);
        fr.setType("success");
        fr.setMessage("操作成功。");
        return fr;
    }

    /**
     * 确认到账页面
     */
    @RequestMapping("/money_ok_page")
    @RequestAuth
    public String moneyOkPage(HttpServletRequest request,int id,Model model){
        UserInfo user = userInfoService.adminUserOne(id);
        model.addAttribute("user",user);
        if (user.getPushUid()>0) {
            model.addAttribute("pusher", userInfoService.adminUserOne(user.getPushUid()));
        }
        if (user.getGradePushUid()>0) {
            model.addAttribute("gradePusher", userInfoService.adminUserOne(user.getGradePushUid()));
        }
        return "mgr/user/money_ok";
    }

    @RequestMapping("/money_ok")
    @ResponseBody
    @RequestAuth
    public FormResultBean moneyOk(HttpServletRequest request,int id,double totAmount) {
        FormResultBean fr = new FormResultBean();
        UserInfo user = userInfoService.adminUserOne(id);
        int payAmount = (int)(totAmount*100);
        //System.out.println("====================="+payAmount);
        vipOrderService.orderAdd(user,10,payAmount);
        fr.setType("success");
        fr.setMessage("操作成功。");
        return fr;
    }

    /**
     * 修改推广人
     * @param request
     * @return
     */
    @RequestMapping("/pusher_replace_page")
    @RequestAuth
    public String replacePusherPage(HttpServletRequest request,int uid,Model model){
        model.addAttribute("uid",uid);
        return "mgr/user/pusher_replace";
    }
    @RequestMapping("/pusher_replace")
    @ResponseBody
    @RequestAuth
    public FormResultBean replacePusher(HttpServletRequest request, int uid,String userName,String officialServiceNumber) {
        FormResultBean fr = new FormResultBean(Status.HTTP_OK.value());
        UserInfo userInfo = userInfoService.adminUserOne(uid);
        if(userInfo==null){
            return fr.setType("error").setMessage("用户不存在");
        }

        UserInfo pusher = null;
        if (StrUtil.isNotBlank(userName)){
            pusher = userInfoService.adminUserByUserName(userName);
        }else if (StrUtil.isNotBlank(officialServiceNumber)){
            String queryOfficialServiceNumber = null;
            if (officialServiceNumber.contains("CAZF")){
                queryOfficialServiceNumber = officialServiceNumber.substring(5);
            }else {
                queryOfficialServiceNumber = officialServiceNumber;
            }
            pusher = userInfoService.adminUserByOfficialServiceNumber(queryOfficialServiceNumber);
        }

        if (pusher==null){
            return fr.setType("error").setMessage("推广人不存在");
        }

        userInfo.setPushUid(pusher.getId());
        userInfo.setGradePushUid(pusher.getPushUid());

        userInfoService.save(userInfo);

        return fr.setType("success").setMessage("修改成功");
    }
}
